//
//  BrandLibraryVc.swift
//  Pods
//
//  Created by eme on 2017/4/12.
//
//

import UIKit
import UtilCore
import MJRefresh
import RxSwift
import EmptyDataView
import RickonCore

class BrandLibraryVc: Empty_TVc {
    
    /****************************Storyboard UI设置区域****************************/
    
    @IBOutlet weak var customTableView: UITableView!
    
    /*----------------------------   自定义属性区域    ----------------------------*/
    var brandArr = [BrandListModel](){
        didSet{
            self.customTableView.reloadData()
        }
    }
    var indexArr = [String]()
    
    var a = 0
    
    var brandlist:[(title:String,arr:[BrandListModel])] = []
    
    //    var relList:[(title:String,arr:[String])] = []
    //        {
    //        didSet{
    //            self.customTableView.reloadData()
    //            print(a++)
    //        }
    //    }
    
    var brandListVm:GetMoreBrandListVm?
    
    let brandHearder = MJRefreshNormalHeader()                      //品牌顶部刷新
    
    let brandFooter = MJRefreshAutoNormalFooter()                   //品牌底部加载更多
    
    /****************************Storyboard 绑定方法区域****************************/
    
    
    
    /**************************** 以下是方法区域 ****************************/
    override func viewDidLoad() {
        super.viewDidLoad()
        self.navigationController?.setNavigationBarHidden(false, animated: true)
        
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        
    }
    /**
     界面基础设置
     */
    override func setupUI() {
        /**
         *  自定义 导航栏左侧 返回按钮
         */
        self.customLeftBarButtonItem()
        self.setUptableView()
    }
    func setUptableView(){
        
        self.customTableView.showsVerticalScrollIndicator = false
        
        customTableView.delegate = self
        customTableView.tableFooterView = UIView()
        customTableView.sectionIndexColor = UIColor(hex:"92969c")
        customTableView.sectionIndexBackgroundColor = UIColor.clear

        customTableView.dataSource = self
    }
    func setUpStringArr(){
        
        for str in self.brandArr{
            let newStr = str.brcode.transformToPinYin()
            indexArr.append(newStr.substring(to: newStr.index(newStr.startIndex, offsetBy: 1)).uppercased())
            
        }
        //去重并排序
        indexArr = Set(indexArr).sorted(by: <)
        
        for first in indexArr{
            
            var relItem:(title:String,arr:[BrandListModel]) = (title:first,arr:[])
            
            for str in brandArr
            {
                if str.brcode.transformToPinYin().substring(to: str.brcode.index(str.brcode.startIndex, offsetBy: 1)).uppercased() == relItem.title{
                    
                    relItem.arr.append(str)
                }
            }
            brandlist.append(relItem)
        }
        self.customTableView.reloadData()
    }
    func brandHeaderRefresh(){
        
        self.customTableView.mj_header.endRefreshing()
    }
    func brandFooterRefresh(){
        
        self.customTableView.mj_footer.endRefreshing()
    }
    /**
     绑定到viewmodel 设置
     */
    override func bindToViewModel(){
        self.brandListVm = GetMoreBrandListVm(
            input:(
                refreshTriger:  rx.sentMessage(#selector(BrandLibraryVc.viewWillAppear)).map { _ in () },
                loadMoreTriger: rx.sentMessage(#selector(BrandLibraryVc.brandFooterRefresh)).map { _ in () }
            )
        )
        
        self.brandListVm?
            .backDate
            .asObservable()
            .skip(1)
            .do(onNext: { [unowned self] _ in
                
                self.errorPageView.isHidden = true
        
        }).subscribe(onNext:{ [unowned self] brandList in
            
            self.showEmptyView = true
            self.brandArr = brandList
            self.setUpStringArr()
            
            }).addDisposableTo(disposeBag)
        
        
        self.brandListVm?
            .hasNextPage
            .asDriver()
            .asObservable()
            .subscribe(onNext:{ hasNextPage in
                
            if !hasNextPage{
                self.brandFooter.endRefreshingWithNoMoreData()
            }else{
                self.brandFooter.resetNoMoreData()
            }
        }).addDisposableTo(disposeBag)
        
        self.brandListVm?.loading.asObservable().bindTo(self.view.rx_loading).addDisposableTo(disposeBag)
        
        self.brandListVm?.error.bindTo(self.view.rx_error).addDisposableTo(disposeBag)
    }
}
extension BrandLibraryVc:UITableViewDelegate,UITableViewDataSource{
    func numberOfSections(in tableView: UITableView) -> Int {
        
        return indexArr.count
        
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return brandlist[section].arr.count
    }
    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        if indexArr.count > section{
            return indexArr[section]
        }else{
            return ""
        }
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! BrandListTableViewCell
        cell.brandNameLabel?.text = brandlist[indexPath.section].arr[indexPath.row].brname
        cell.brandImageView.setUrlImage(brandlist[indexPath.section].arr[indexPath.row].brlogourl)
        return cell
    }
    func sectionIndexTitles(for tableView: UITableView) -> [String]? {
        return indexArr
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        _ = "brandpage".openURL(["brid":brandlist[indexPath.section].arr[indexPath.row].brid])
    }
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 27.5
    }
}

